package net.dgg.dggcloud.service.jrcrm.service.orf;

import net.dgg.dggcloud.core.idwork.KeyWorker;
import net.dgg.dggcloud.core.minidao.hibernate.dao.IGenericBaseCommonDao;
import net.dgg.dggcloud.service.common.base.service.BaseService;
import net.dgg.dggcloud.service.jrcrm.constant.CustomerRecordConstant;
import net.dgg.dggcloud.service.jrcrm.dao.orf.OrderDao;
import net.dgg.dggcloud.service.jrcrm.dao.orf.PayCostRecordDao;
import net.dgg.dggcloud.service.jrcrm.dao.orf.PerformanceDao;
import net.dgg.dggcloud.service.jrcrm.dao.orf.ReimburseDao;
import net.dgg.dggcloud.service.jrcrm.entity.orf.Order;
import net.dgg.dggcloud.service.jrcrm.entity.orf.PaymentCostRecord;
import net.dgg.dggcloud.service.jrcrm.entity.orf.PerformancePrefit;
import net.dgg.dggcloud.service.jrcrm.entity.orf.Reimburse;
import net.dgg.dggcloud.service.entity.user.User;
import net.dgg.dggcloud.service.jrcrm.service.business.BusinessAbilityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 财务 退款
 *
 * @author 郭伟 2017/11/2
 */
@Service
public class ReimburseService extends BaseService {

    @Autowired
    private ReimburseDao reimburseDao;

    @Resource(name="miniDaoHiberCommonDao")
    protected IGenericBaseCommonDao repository;


    @Autowired
    private PayCostRecordDao payCostRecordDao;

    @Autowired
    private PerformanceDao performanceDao;

    @Autowired
    private PaymentAuditorRecordService paymentAuditorRecordService;

    @Autowired
    private BusinessAbilityService businessAbilityService;

    @Autowired
    private OrderDao orderDao;

    /**
     *  根据ID，查询退款相关数据
     * @param id
     * @return
     */
    @Deprecated
    public Reimburse getByIdHiber(Long id){
        return this.repository.get(Reimburse.class,id);
    }


    /**
     *  根据参数 ，获取退款列表数据数量
     * @param map
     * @return
     */
    public Integer countReimburseByMap(Map map) {
        return reimburseDao.countReimburseByMap(map);
    }

    /**
     *  根据参数 ，获取退款列表数据
     * @param map
     * @return
     */
    public List<Map> listReimburseByMap(Map map) {
        return reimburseDao.listReimburseByMap(map);
    }


    /**
     *  保存退款
     * @param reimburse
     * @param user
     * @return
     */
    public Long saveReimburse(Reimburse reimburse, List<PaymentCostRecord> exPayCostRecord, List<PaymentCostRecord> inPayCostRecord, List<PerformancePrefit> performancePrefits, User user){
        reimburse.setCreateUser(user);
        reimburse.setUpdaterUser(user);

        // 保存外部成本
        if(null != exPayCostRecord && exPayCostRecord.size() > 0){
            for (int i = 0; i < exPayCostRecord.size(); i++) {
                Long exId = this.keyWorker.nextId();
                PaymentCostRecord cost = exPayCostRecord.get(i);
                cost.setCreateUser(user);
                cost.setUpdaterUser(user);
                cost.setPaymentId(reimburse.getId());
                cost.setNotAmount(cost.getAmount());
                cost.setAmount(cost.getAmount());
                cost.setType(1);
                cost.setStatus(1);
                cost.setId(exId);
                cost.setOrderBusinessId(reimburse.getOrderBusinessId());
                payCostRecordDao.saveByHiber(cost);
            }
        }


        // 保存内部成本
        if(null != inPayCostRecord && inPayCostRecord.size() > 0){
            for (int i = 0; i < inPayCostRecord.size(); i++) {
                Long inId = this.keyWorker.nextId();
                PaymentCostRecord cost = inPayCostRecord.get(i);
                cost.setCreateUser(user);
                cost.setUpdaterUser(user);
                cost.setPaymentId(reimburse.getId());
                cost.setNotAmount(cost.getAmount());
                cost.setAmount(cost.getAmount());
                cost.setType(1);
                cost.setStatus(2);
                cost.setId(inId);
                cost.setOrderBusinessId(reimburse.getOrderBusinessId());
                payCostRecordDao.saveByHiber(cost);
            }
        }



        Order order = this.repository.get(Order.class,reimburse.getOrderId());

        //业绩利润
        if(null != performancePrefits && performancePrefits.size() > 0){
            for (int i = 0; i < performancePrefits.size(); i++) {
                Long perId = this.keyWorker.nextId();
                PerformancePrefit cost = performancePrefits.get(i);
                cost.setCreateUser(user);
                cost.setUpdaterUser(user);
                cost.setPaymentId(reimburse.getId());
                cost.setPerformanceAmount(0-cost.getPerformanceAmount());
                cost.setProfitAmount(0-cost.getProfitAmount());
                cost.setId(perId);
                cost.setType(2);
                if(cost.getUserType().equals("qdr")){
                    cost.setSignOrgId(order.getOrganizationId());
                }else{
                    User signUser =  this.repository.get(User.class,cost.getSignUserId());
                    cost.setSignOrgId(signUser.getOrgId());
                }
//                User signUser =  this.repository.get(User.class,cost.getSignUserId());
//                cost.setSignOrgId(signUser.getOrgId());
                cost.setOrderId(reimburse.getOrderId());
                cost.setOrderBusinessId(reimburse.getOrderBusinessId());
                performanceDao.saveByHiber(cost);

            }
        }

        reimburseDao.saveByHiber(reimburse);
        return reimburse.getId();
    }


    /**
     *  更新退款
     * @param reimburse
     * @param user
     * @return
     */
    public Long updateReimburse(Reimburse reimburse, List<PaymentCostRecord> exPayCostRecord, List<PaymentCostRecord> inPayCostRecord, List<PerformancePrefit> performancePrefits, User user){
        reimburse.setUpdaterUser(user);

        // 删除内外部成本记录
        Map costmap = new HashMap();
        costmap.put("type",1);
        costmap.put("paymentId",reimburse.getId());
        payCostRecordDao.deletePayCostRecordList(costmap);
        // 保存外部成本
        if(null != exPayCostRecord && exPayCostRecord.size() > 0){
            for (int i = 0; i < exPayCostRecord.size(); i++) {
                Long exId = this.keyWorker.nextId();
                PaymentCostRecord cost = exPayCostRecord.get(i);
                cost.setCreateUser(user);
                cost.setUpdaterUser(user);
                cost.setPaymentId(reimburse.getId());
                cost.setNotAmount(cost.getAmount());
                cost.setAmount(cost.getAmount());
                cost.setType(1);
                cost.setStatus(1);
                cost.setId(exId);
                cost.setOrderBusinessId(reimburse.getOrderBusinessId());
                payCostRecordDao.saveByHiber(cost);
            }
        }


        // 保存内部成本
        if(null != inPayCostRecord && inPayCostRecord.size() > 0){
            for (int i = 0; i < inPayCostRecord.size(); i++) {
                Long inId = this.keyWorker.nextId();
                PaymentCostRecord cost = inPayCostRecord.get(i);
                cost.setCreateUser(user);
                cost.setUpdaterUser(user);
                cost.setPaymentId(reimburse.getId());
                cost.setNotAmount(cost.getAmount());
                cost.setAmount(cost.getAmount());
                cost.setType(1);
                cost.setStatus(2);
                cost.setId(inId);
                cost.setOrderBusinessId(reimburse.getOrderBusinessId());
                payCostRecordDao.saveByHiber(cost);
            }
        }


        // 删除业绩记录
        costmap.put("type",2);
        performanceDao.deletePerformanceList(costmap);

        Order order = this.repository.get(Order.class,reimburse.getOrderId());
        //业绩利润
        if(null != performancePrefits && performancePrefits.size() > 0){
            for (int i = 0; i < performancePrefits.size(); i++) {
                Long perId = this.keyWorker.nextId();
                PerformancePrefit cost = performancePrefits.get(i);
                cost.setCreateUser(user);
                cost.setUpdaterUser(user);
                if(cost.getUserType().equals("qdr")){
                    cost.setSignOrgId(order.getOrganizationId());
                }else{
                    User signUser =  this.repository.get(User.class,cost.getSignUserId());
                    cost.setSignOrgId(signUser.getOrgId());
                }
                cost.setPaymentId(reimburse.getId());
                cost.setPerformanceAmount(0-cost.getPerformanceAmount());
                cost.setProfitAmount(0-cost.getProfitAmount());
                cost.setId(perId);
                cost.setType(2);
//                User signUser =  this.repository.get(User.class,cost.getSignUserId());
//                cost.setSignOrgId(signUser.getOrgId());
                cost.setOrderId(reimburse.getOrderId());
                cost.setOrderBusinessId(reimburse.getOrderBusinessId());
                performanceDao.saveByHiber(cost);

            }
        }

        reimburseDao.updateByHiber(reimburse);
        return reimburse.getId();
    }


    public void saveAudit(User user,String auditUserId,String paymentId){
        String[] paymentIds = paymentId.split(",");
        String cStatus= "ORF_TKZT_1";
        String code="";

        if(null != paymentIds && paymentIds.length > 0){
            for (int i = 0; i < paymentIds.length; i++) {
                Reimburse orderPayRecord =  this.repository.get(Reimburse.class,Long.valueOf(paymentIds[i]));
                if(null!=orderPayRecord){
                    if(1==orderPayRecord.getReimburseType() || 3==orderPayRecord.getReimburseType()){
                        code = "ORF_TKZT_2";
                    }else if(2==orderPayRecord.getReimburseType()){
                        code = "ORF_TKZT_4";
                    }
                    orderPayRecord.setReimburseStatus(code);

                    orderPayRecord.setCurrentAuditorUserId(Long.valueOf(checkAudit(auditUserId)));
                    reimburseDao.updateByHiber(orderPayRecord);
                }

                paymentAuditorRecordService.saveRecord(user,Long.valueOf(paymentIds[i]),"",2,0,cStatus);
            }
        }
    }


    public String checkAudit(String auditUserId){
        return auditUserId.substring(auditUserId.lastIndexOf("_")+1,auditUserId.length());
    }

    public List<Map> getReimburseByMap(Map map){
        return reimburseDao.getReimburseByMap(map);
    }

    public void
    updateReimburseAudit(User user,Long reimburseId,String nodeName,Long auditUserId,String content){
        Reimburse reimburse = this.repository.get(Reimburse.class,reimburseId);
        if (null != reimburse){
            reimburse.setReimburseStatus(nodeName);
            reimburse.setCurrentAuditorUserId(auditUserId);
            if("ORF_TKZT_9".equals(nodeName)){
                reimburse.setRejectReason(content);
                reimburse.setRejectTime(new Date());
            }

            //完成，更新时间
            if(nodeName.equals("ORF_TKZT_8")){
                reimburse.setCarryOutTime(new Date());
                //更新退款明细中的状态为完成
                List<PaymentCostRecord> list = this.repository.findByProperty(PaymentCostRecord.class,"paymentId",reimburseId);
                Long totalInCost = 0L;
                Long totalExCost = 0L;
                if(null != list && list.size() > 0){
                    for(PaymentCostRecord pc:list) {
                        pc.setIsComplete(1);
                        if(pc.getStatus() == 1){
                            totalExCost = totalExCost + pc.getAmount();
                        }else{
                            totalInCost = totalInCost + pc.getAmount();
                        }
                        payCostRecordDao.updateByHiber(pc);
                    }
                }

                List<PerformancePrefit> listper = this.repository.findByProperty(PerformancePrefit.class,"paymentId",reimburseId);

                Long totalPerformance = 0L;
                Long totalProfit = 0L;
                if(null != listper && listper.size() > 0){
                    for(PerformancePrefit pc:listper) {
                        pc.setIsComplete(1);
                        totalPerformance = totalPerformance + pc.getPerformanceAmount();
                        totalProfit = totalProfit + pc.getProfitAmount();
                        performanceDao.updateByHiber(pc);
                    }
                }
                // 更新订单状态
                Order order =this.repository.get(Order.class,reimburse.getOrderId());
                order.setAmount(order.getAmount() - reimburse.getAmount());
                order.setInternalCost(order.getInternalCost()+totalInCost);
                order.setExternalCost(order.getExternalCost()+totalExCost);
                order.setAchievement(order.getAchievement()+totalPerformance);
                order.setProfit(order.getProfit()+totalProfit);
//                order.setStatus("ORF_DDZT_3");
                orderDao.updateByHiber(order);
//                if(reimburse.getReimburseType() == 2 || reimburse.getReimburseType() == 3){
//                    // 退单更新商机
//                    businessAbilityService.updateBusinessOrderInfo(order.getBusinessId(),user.getId(), CustomerRecordConstant.BUS_OPERATE_BACKORDER);
//                }
            }
        }
        this.repository.saveOrUpdate(reimburse);
    }

    public List<Map> getAuditReimburseListByMap(Map map){
        return reimburseDao.getAuditReimburseListByMap(map);
    }

    /**
     * 根据订单获取所有的退款记录
     * @param orderId 订单id
     * @return
     */
    public List<Reimburse> getAllReimburseListByOrderId(Long orderId){
        return this.repository.findByProperty(Reimburse.class,"orderId",orderId);
    }

    /**
     * 根据订单id获取所有子订单信息
     * @param map
     * @return
     */
    public List<Map> getOrderBusinessListByMap(Map map){
        return reimburseDao.getOrderBusinessListByMap(map);
    }


    /**
     *  查询当前生产订单，有无未完成的退款申请
     * @param map
     * @return
     */
    public List<Map> getNotCompleteReimburse(Map map){
        return reimburseDao.getNotCompleteReimburse(map);
    }
}
